package com.liyujie.networkrequest.utils;

import com.arcsoft.asg.libcommon.util.business.rx.RxUtils;
import com.arcsoft.asg.libcommon.util.common.DeviceUtils;
import com.arcsoft.asg.libcommon.util.common.TimeUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

public class RebootUtils {

    private static Disposable rebootDisposable;

    public static void startRebootEveryDayTask(){
        int hour = 4;
        int min = 30;
        long current = System.currentTimeMillis();
        long zero = TimeUtils.getStartTimeOfDay();
        long taskTime = hour * 1000L * 3600 + min * 1000 * 60;
        //今日任务执行时间
        long todayTime = zero + taskTime;
        long sub = todayTime - current;
        if (sub > 0 && null == rebootDisposable) {
            rebootDisposable = Observable.timer(sub, TimeUnit.MILLISECONDS)
                    .compose(RxUtils.computingToMain())
                    .subscribe(aLong -> deviceReboot());
        }
    }


    private static void deviceReboot() {
        boolean flag1 = false;
        boolean flag2 = false;
        try {
            DeviceUtils.reboot();
        } catch (Exception e) {
            flag1 = true;
        }
        try {
            DeviceUtils.reboot("");
        } catch (Exception e) {
            flag2 = true;
        }
        if (flag1 && flag2) {
            InitializeUtils.getDefaultMaker().show("设备重启失败，请检查应用是否有系统权限");
        }
    }
}
